/*
 *  network.h
 *  
 *  Created by James Dykstra
 *	Team 5
 *
 *  Copyright 2010 Michigan Technological University. All rights reserved.
 */

#ifndef NET_H
#define NET_H
#include "SDL/SDL_net.h"
#include "opponent.h"
#include "Sound.h"
#include <fstream>
#include <sstream>

#define MAX_CLIENTS 4

class Network
{
public:
	Network(char *);
	~Network();

	bool open();
	void close();

	UDPpacket* recvPacket();
	std::string extractData(UDPpacket*);

	bool sendAll(std::string data, int excn, bool addId);
	bool send(std::string data, int cn, bool addId);
	bool send(std::string data);

	bool connected(){ return (servSock != NULL); };
	bool isActive(){ return active; };
	bool isServer(){ return server; };

	void setOpponents(Opponent*[]);
	void setClientNum(int cn){ clientNum = cn; };
	int getCur(){ return cur; };

	bool newPlayerConnected(UDPpacket *);
	void removeClient(int);
	void updateOpponents(int);

	bool setSound(Sound*);
	bool setPlayer(Fighter*);

	char * getIP(){ return ip; };
	int getClientNum(){ return clientNum; };
	Opponent* getOpponent(int cn);
	Fighter* getPlayer(){ return player; };
	Sound* getSound(){ return sound; };

	class ProtocolParser
	{
	public:
		template <class T>
		static std::string numToStr(T num)
		{
			std::stringstream ss;
			ss<<num;
			return ss.str();
		}
		static std::string extractVal(std::string src, char val)
		{
			size_t xp = src.find_first_of(val);
			if(xp == std::string::npos)
				return "";

			xp+=2;
			if(xp > src.length())
				return "";

			size_t endp = src.find_first_of(xp, ':');
			if(endp == std::string::npos)
				endp = src.length();
			else
				endp-=2;

			return src.substr(xp, endp);
		}
		static int extractiVal(std::string src, char val)
		{
			std::string tmp = extractVal(src, val);
			if(tmp.empty())
				return -1;

			std::stringstream ss;
			ss<<tmp;

			int v;
			return (ss>>v?v:-1);
		}
		static float extractfVal(std::string src, char val)
		{
			std::string tmp = extractVal(src, val);
			if(tmp.empty())
				return -1;

			std::stringstream ss;
			ss<<tmp;

			float v;
			return (ss>>v?v:-1);
		}
	};
	
private:
	IPaddress			opp[MAX_CLIENTS];
	int				cur;
	int				clientNum;
	char			*ip;
	UDPsocket		servSock;
	UDPsocket		sendSock;
	UDPpacket		*packet;
	bool				active;
	bool				server;
	Opponent			*minions[MAX_CLIENTS];
	Fighter			*player;
	Sound			*sound;
};

#endif

